import pandas as pd
import numpy as np
from pandas import DataFrame,Series
from sklearn.cluster import KMeans
from sklearn.cluster import Birch

data = pd.read_excel('聚类2.xls') # datafile是excel文件，所以用read_excel,如果是csv文件则用read_csv
d = DataFrame(data)
d.head()

# 聚类
mod = KMeans(n_clusters=6, n_jobs=4, max_iter=500)  # 聚成3类数据,并发数为4，最大循环次数为500
mod.fit_predict(d)  # y_pred表示聚类的结果
print(mod.cluster_centers_)
# 给每一条数据标注上被分为哪一类
r = pd.concat([d, pd.Series(mod.labels_, index=d.index)], axis=1)
r.columns = list(d.columns) + ['聚类类别']
r.to_excel('聚类结果.xls')  # 如果需要保存到本地，就写上这一列

# 可视化过程
from sklearn.manifold import TSNE

ts = TSNE()
ts.fit_transform(r)
ts = pd.DataFrame(ts.embedding_, index=r.index)

import matplotlib.pyplot as plt

a = ts[r['聚类类别'] == 0]
print(a)
plt.scatter(a[0], a[1], color="green")
a = ts[r['聚类类别'] == 1]
plt.scatter(a[0], a[1], color="black")
a = ts[r['聚类类别'] == 2]
plt.scatter(a[0], a[1], color="red")
a = ts[r['聚类类别'] == 3]
plt.scatter(a[0], a[1], color="gray")
a = ts[r['聚类类别'] == 4]
plt.scatter(a[0], a[1], color="yellow")
plt.show()
